package com.lzxuni.modules.wechat.onlineservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzxuni.common.utils.R;
import com.lzxuni.common.utils.web.OkHttpUtil;
import com.lzxuni.modules.wechat.config.controller.WeChatController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微客服
 * Created by 潘云明
 * 2019/7/26 14:48
 */
@RestController
@RequestMapping("/wechat")
public class OnlineServiceController extends WeChatController {


    @RequestMapping(value = "/onlineservice_index")
    public ModelAndView onlineservice_index() {
        ModelAndView mv = new ModelAndView("/wechat/onlineservice/onlineservice");
        //获取客服在线状态
        String onlineKfUrl = "https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=ACCESS_TOKEN";
        String onlineKfStr = OkHttpUtil.httpPost(onlineKfUrl.replace("ACCESS_TOKEN", getAccessToken()));
        System.out.println("onlineKfStr："+onlineKfStr);
        Map<String, String> map = new HashMap<>();
        JSONObject onlineKf_jo = JSON.parseObject(onlineKfStr);
        JSONArray onlineKf_ja = (JSONArray) onlineKf_jo.get("kf_online_list");
        for (int i = 0; i < onlineKf_ja.size(); i++) {
            JSONObject jo = (JSONObject) onlineKf_ja.get(i);
            map.put(jo.getString("kf_account"), (String) jo.getString("status"));
        }
        //获取客服列表
        String kfUrl = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=ACCESS_TOKEN";
        String kfStr = OkHttpUtil.httpPost(kfUrl.replace("ACCESS_TOKEN", getAccessToken()));
        System.out.println("kfStr："+kfStr);
        JSONObject jsonObject = JSON.parseObject(kfStr);
        JSONArray jsonArray = (JSONArray) jsonObject.get("kf_list");
        List<Map<String, String>> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jo = (JSONObject) jsonArray.get(i);
            Map<String, String> map_temp = new HashMap<>();
            map_temp.put("kf_nick", jo.getString("kf_nick"));  //客服名称
            String imgUrl = jo.getString("kf_headimgurl");
            map_temp.put("kf_headimgurl", imgUrl.substring(0, imgUrl.length() - 4) + "png");  //客服头像
            map_temp.put("kf_account", jo.getString("kf_account"));  //客服账号
            if ("1".equals(map.get(map_temp.get("kf_account")))) {
                map_temp.put("status", "1");  //客服在线
            } else {
                map_temp.put("status", "0");  //客服不在线
            }
            list.add(map_temp);
        }
        String Kf = JSON.toJSONString(list);
        System.out.println("Kf：" + Kf);
        mv.addObject("KEFU", Kf);

        return mv;
    }

    @RequestMapping(value = "/onlineservice_connect")
    public Object onlineservice_connect(HttpServletRequest req, HttpServletResponse res, String kf_account, String kf_nick) throws Exception {
        String connJson = "{\"kf_account\" : \"" + kf_account + "\", \"openid\" : \"" + getOpenId(req) + "\" }";
        String connUrl = "https://api.weixin.qq.com/customservice/kfsession/create?access_token=ACCESS_TOKEN";
        String connResult = OkHttpUtil.postJsonParams(connUrl.replace("ACCESS_TOKEN", getAccessToken()), connJson);
        JSONObject conn_jo = JSON.parseObject(connResult);
        System.out.println("connResult：" + connResult);
        //其他人正在服务关闭会话
        if (conn_jo.getString("errcode").equals("65414")) {
            System.out.println("22");
            return R.ok("请关闭其他会话重新尝试");
        }
        if (conn_jo.getString("errcode").equals("0")) {
            String helloJson = "{ \"touser\":\"" + getOpenId(req) + "\",  \"msgtype\":\"text\", \"text\": { \"content\":\"您好，我是" + kf_nick + ",很高兴为您服务！\" }}";
            String helloUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";
            String helloResult = OkHttpUtil.postJsonParams(helloUrl.replace("ACCESS_TOKEN", getAccessToken()), helloJson);
            JSONObject hello_jo = JSON.parseObject(helloResult);
            System.out.println("helloResult：" + helloResult);
            if (hello_jo.getString("errcode").equals("45015")) {
                return R.ok("请关注我们的公众号后重试！");
            }
            if (hello_jo.getString("errcode").equals("0")) {
                return R.ok("0");
            }
        }

        return R.ok("客服系统异常，请稍后再试！");
    }


}
